<template>
  <div class="category">
   <van-sidebar v-model="activeKey" @change="handleChange">
  <van-sidebar-item
    v-for="cate in categories"
    :key="cate.id"
    :title="cate.name"
  />
  </van-sidebar>
  <div class="right">
        <van-grid icon-size="48px" column-num="3" gutter="6px">
        <van-grid-item
          v-for="sub in subCategories"
          :key="sub.id"
          :icon="sub.imageUrl"
          :text="sub.title"
        />
      </van-grid>
  </div>
  </div>
</template>

<script>
import { getCategories, getSubCategories } from '@/api/category'
export default {
  name: 'Category',
  data() {
    return {
      activeKey: 0,
      categories: [],
      subCategories: [],
    }
  },
  async created() {
    try {
      const result = await getCategories()
      // console.log('结果：', result)
      this.categories = result.list.slice(1)
      this.handleChange()
    } catch (error) {
      console.error('错误:', error)
    }
  },
  methods: {
    async handleChange() {
      const id = this.categories[this.activeKey].id
      try {
        const data = await getSubCategories(id)
        this.subCategories = data.categories
      } catch (error) {
        console.error('错误:', error)
      }
    },
  },
}
</script>

<style lang="less" scoped>
  .category {
    display: flex;

    .right {
      flex: 1;
    }
  }
</style>
